<template>
    <h1>用户列表</h1>
    <el-table :data="paginatedData" style="width: 100%">
        <el-table-column prop="id" label="ID号" width="350" align="center" />
        <el-table-column prop="register" label="注册时间" width="250" align="center" />
        <el-table-column prop="account" label="账号" align="center" />
    </el-table>
    <div class="box">
        <el-pagination background layout="prev, pager, next" :total="totalItems" :page-size="pageSize"
            :current-page="currentPage" @current-change="handlePageChange" />
    </div>
</template>

<script lang="ts" setup>
import { AllList } from '../../api/request';
import { ref, onMounted, computed } from 'vue';

interface User {
    id: string;
    register: string;
    account: string;
}

// 使用 ref 创建响应式数据
const tableData = ref<User[]>([]);
const totalItems = ref(0); // 总用户数
const currentPage = ref(1); // 当前页码
const pageSize = ref(8); // 每页显示的条目数

const AllListFn = async () => {
    try {
        const content = await AllList();
        const { code, result } = content;

        if (code === 200) {
            // 更新总用户数
            totalItems.value = result.length;
            const newArr = result.map(item => ({
                id: item.ID号,
                register: item.注册时间,
                account: item.账号
            }));
            tableData.value = newArr;
        }
    } catch (error) {
        console.error('获取用户列表失败:', error);
    }
};

// 计算当前页的数据
const paginatedData = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value;
    return tableData.value.slice(start, start + pageSize.value);
});

// 处理页码变化
const handlePageChange = (page: number) => {
    currentPage.value = page; // 更新当前页码
};

// 使用 onMounted 钩子以确保在组件挂载后调用函数
onMounted(() => {
    AllListFn();
});
</script>

<style>
h1 {
    margin-top: 10px;
    margin-left: 20px;
    font-size: 20px;
    margin-bottom: 10px;
}

.box {
    margin-top: 20px;
    width: 100%;
    height: auto;
    margin: 0 auto;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px 0;
}
</style>